/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Cliente.java
 *
 * Created on 15/04/2010, 11:21:45
 */
package user_gui;

import elemento.ClienteTelefone;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import op.Telefone;

/**
 *
 * @author Jônatas
 */
public class EditaRemoveCliente extends javax.swing.JFrame implements ContainsEmpresa {

    private FramePrincipal parentComponent;
    private ClienteTelefone old;

    /** Creates new form Cliente */
    public EditaRemoveCliente(FramePrincipal parentComponent) {

        this.parentComponent = parentComponent;
        initComponents();
        this.parentComponent.setEnabled(false);
        this.jButton1.setEnabled(false);
        this.jButton2.setEnabled(false);
        this.jTextField1.setEnabled(false);
        this.buttonEmpresas.setEnabled(false);
        this.tfEmpresa.setEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        tfEmpresa = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        buttonEmpresas = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Editar telefone");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Nome:");

        jButton1.setText("Excluir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Alterar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setText("-");

        jTextField2.setDocument(new FixedLengthDocument(3));
        jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField2KeyReleased(evt);
            }
        });

        jLabel5.setText("Telefone:");

        jTextField4.setDocument(new FixedLengthDocument(4));
        jTextField4.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField4KeyReleased(evt);
            }
        });

        jTextField3.setDocument(new FixedLengthDocument(4));
        jTextField3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField3KeyReleased(evt);
            }
        });

        jButton3.setText("Pesquisar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        tfEmpresa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfEmpresaKeyReleased(evt);
            }
        });

        jLabel6.setText("Empresa:");

        buttonEmpresas.setText("...");
        buttonEmpresas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonEmpresasActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonEmpresas)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 72, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton2))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(tfEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6)
                            .addComponent(buttonEmpresas))
                        .addContainerGap())))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-385)/2, (screenSize.height-150)/2, 385, 150);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        this.parentComponent.setEnabled(true);

    }//GEN-LAST:event_formWindowClosing

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        String nome = jTextField1.getText();

        String ddd = jTextField2.getText();
        String num1 = jTextField3.getText();
        String num2 = jTextField4.getText();

        String empresa = tfEmpresa.getText();

        if (ddd.length() == 2) {
            ddd = "0" + ddd;
        } else if (ddd.length() < 2) {
            JOptionPane.showMessageDialog(this, "Preencha o ddd corretamente.", "ERRO", JOptionPane.ERROR_MESSAGE);
            return;
        }


        try {
            Integer.parseInt(ddd);
            Integer.parseInt(num1);
            Integer.parseInt(num2);
        } catch (NumberFormatException numberFormatException) {
            JOptionPane.showMessageDialog(this, "Preencha os campos corretamente.", "ERRO", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String telefoneSimples = ddd + num1 + num2;

        ClienteTelefone cliente = new ClienteTelefone(nome, telefoneSimples);
        if(!empresa.isEmpty()) {
            cliente.setId_empresa(Integer.parseInt(empresa));
        }
        try {
            if (FramePrincipal.COMUNICABD.update(FramePrincipal.tableName, cliente, old)) {
                JOptionPane.showMessageDialog(this, "O cadastro foi alterado com sucesso.");
                old = cliente;
                this.jTextField1.setText(old.getNome());
                this.jTextField2.setText(ddd);

            } else {
                JOptionPane.showMessageDialog(this, "Ocorreu um erro durante o cadastro.");

            }
        } catch (SQLException ex) {
            Logger.getLogger(FramePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        int resposta = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja excluir o registro?",
                "ATENÇÃO", JOptionPane.YES_NO_OPTION);

        if (resposta == 0) {
            try {

                boolean b = FramePrincipal.COMUNICABD.delete(FramePrincipal.tableName, old.getTelefone());

                if (b) {
                    JOptionPane.showMessageDialog(this, "A entrada foi removida com sucesso.");

                    old = null;

                    this.jTextField1.setText("");
                    this.jTextField2.setText("");
                    this.jTextField3.setText("");
                    this.jTextField4.setText("");

                    this.jButton1.setEnabled(false);
                    this.jButton2.setEnabled(false);
                    this.jTextField1.setEnabled(false);

                    return;
                }

            } catch (SQLException ex) {
                Logger.getLogger(EditaRemoveCliente.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        String ddd = jTextField2.getText();
        String num1 = jTextField3.getText();
        String num2 = jTextField4.getText();

        if (ddd.length() == 2) {
            ddd = "0" + ddd;
        } else if (ddd.length() < 2) {
            JOptionPane.showMessageDialog(this, "Preencha o ddd corretamente.", "ERRO", JOptionPane.ERROR_MESSAGE);
            return;
        }


        try {
            Integer.parseInt(ddd);
            Integer.parseInt(num1);
            Integer.parseInt(num2);
        } catch (NumberFormatException numberFormatException) {
            JOptionPane.showMessageDialog(this, "Preencha os campos corretamente.", "ERRO", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Telefone telefoneCompleto = new Telefone(ddd, num1, num2);

        String telefone = telefoneCompleto.toString();
        telefone = telefone.replace(" ", "");
        telefone = telefone.replace("-", "");
        telefone = telefone.replace("(", "");
        telefone = telefone.replace(")", "");



        try {
            ClienteTelefone cliente = FramePrincipal.COMUNICABD.select(FramePrincipal.tableName, telefone);

            if (cliente == null) {
                JOptionPane.showMessageDialog(this, "Número não encontrado.", "ERRO", JOptionPane.ERROR_MESSAGE);
                return;
            }

            old = cliente;
            this.jButton1.setEnabled(true);
            this.jButton2.setEnabled(true);
            this.jTextField1.setEnabled(true);
            this.buttonEmpresas.setEnabled(true);
            this.tfEmpresa.setEnabled(true);

            this.jTextField2.setText(ddd);
            this.jTextField1.setText(old.getNome());
            this.tfEmpresa.setText("" + cliente.getId_empresa());

        } catch (SQLException ex) {
            Logger.getLogger(CadastraCliente.class.getName()).log(Level.SEVERE, null, ex);
        }




    }//GEN-LAST:event_jButton3ActionPerformed

    private void jTextField2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyReleased
        if (jTextField2.getText().length() >= 3) {
            jTextField3.requestFocus();
        }
    }//GEN-LAST:event_jTextField2KeyReleased

    private void jTextField3KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField3KeyReleased
        if (jTextField3.getText().length() >= 4) {
            jTextField4.requestFocus();
        }
    }//GEN-LAST:event_jTextField3KeyReleased

    private void jTextField4KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField4KeyReleased
        if (jTextField4.getText().length() >= 4) {
            jButton3.requestFocus();
        }
    }//GEN-LAST:event_jTextField4KeyReleased

    private void tfEmpresaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfEmpresaKeyReleased
        // TODO add your handling code here:
}//GEN-LAST:event_tfEmpresaKeyReleased

    private void buttonEmpresasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEmpresasActionPerformed
        ListaEmpresas empresas = new ListaEmpresas(this);
        empresas.setVisible(true);
}//GEN-LAST:event_buttonEmpresasActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonEmpresas;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField tfEmpresa;
    // End of variables declaration//GEN-END:variables

    public void setEmpresaText(String idEmpresa) {
        tfEmpresa.setText(idEmpresa);
    }
}
